<template>
  <view class="container">
    <view class="search-box">
      <u-input v-model="keywords" placeholder="请输入地址" :clearable="true" @input="querySearch">
        <template slot="suffix">
          <u-icon name="search" size="20"></u-icon>
        </template>
      </u-input>

      <!-- 搜索结果列表 -->
      <view class="search-list" v-if="searchResults.length > 0">
        <view class="search-item" v-for="(item, index) in searchResults" :key="index" @tap="handleSelect(item)">
          <view class="item-name">{{ item.name }}</view>
          <view class="item-address">
            {{ item.address.context[0].name }}
            {{ item.address.context[1].name }}
            {{ item.address.context[2].name }}
          </view>
        </view>
      </view>
    </view>

    <!-- 地图容器 -->
    <view id="map" class="map" ref="container"></view>
    <!-- 底部按钮 -->
    <view class="bottom-btns">
      <u-button @click="handleCancel" type="default" plain>取消</u-button>
      <u-button @click="handlerSelectConfirm" type="primary">确定</u-button>
    </view>
  </view>
</template>

<script>
const mapKey = 'Cq5k13fcUNmZCyzpI7szHrVdF5pwH9O6';

export default {
  data() {
    return {
      keywords: '',
      searchResults: [],
      container: null,
      map: null,
      infoWindow: null,
      markerLayer: null,
      userlocation: {},
    };
  },

  mounted() {
    // 动态创建地图资源
    console.log('document', document);
    if (typeof document !== 'undefined') {
      // 检查是否已存在地图资源
      if (!document.querySelector('#aimap-script')) {
        const script = document.createElement('script');
        script.id = 'aimap-script';
        script.src = 'https://location-dev.newayz.com/aimap-gl-js/v2.6.0/aimap-gl.js';
        script.onload = () => {
          console.log('地图脚本加载完成');
          this.initLocation();
        };
        document.head.appendChild(script);
      }

      if (!document.querySelector('#aimap-style')) {
        const link = document.createElement('link');
        link.id = 'aimap-style';
        link.rel = 'stylesheet';
        link.href = 'https://location-dev.newayz.com/aimap-gl-js/v2.6.0/aimap-gl.css';
        document.head.appendChild(link);
      }
    } else {
      console.warn('document对象不可用，地图资源未加载');
    }
  },

  methods: {
    open() {
      // 等待aimap加载完成
      console.log('aimap加载完成');
      this.initLocation();
    },
    // 获取省市区信息的辅助函数
    getRegionInfo(context) {
      if (!context || !Array.isArray(context)) return { province: '', city: '', district: '', provinceCode: '0', cityCode: '0', districtCode: '0' };
      
      let province = '';
      let city = '';
      let district = '';
      let provinceCode = '0';
      let cityCode = '0';
      let districtCode = '0';
      
      // 通过type字段匹配，而不是通过索引
      for (const item of context) {
        if (item.type === 'Province') {
          province = item.name || '';
          provinceCode = item.code || '0';
        } else if (item.type === 'City') {
          city = item.name || '';
          cityCode = item.code || '0';
        } else if (item.type === 'District') {
          district = item.name || '';
          districtCode = item.code || '0';
        }
      }
      
      // 如果在长沙，使用固定值
      if (province.includes('湖南') || city.includes('长沙')) {
        provinceCode = '430000';
        cityCode = '430100';
      }
      
      return { province, city, district, provinceCode, cityCode, districtCode };
    },

    // 初始化地图
    async initMap(position) {
      let lat = '';
      let lng = '';

      if (this.longitude) {
        lng = this.longitude;
        lat = this.latitude;
      } else if (position && position.latitude) {
        lng = position.longitude;
        lat = position.latitude;
      } else {
        lng = '116.307484';
        lat = '39.98412';
      }

      // 初始化地图
      aimap.accessToken = mapKey;
      this.map = new aimap.Map({
        container: 'map',
        center: [lng, lat],
        zoom: 15.2,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
      });

      const addressInfo = await this.getAddressInfo({ lng, lat });
      
      // 获取省市区信息
      let { province, city, district, provinceCode, cityCode, districtCode } = { province: '', city: '', district: '', provinceCode: '0', cityCode: '0', districtCode: '0' };
      
      if (addressInfo && addressInfo.address && addressInfo.address.context) {
        try {
          const context = addressInfo.address.context;
          
          console.log('初始位置context数据:', context);
          
          // 使用辅助函数获取省市区信息
          const regionInfo = this.getRegionInfo(context);
          province = regionInfo.province;
          city = regionInfo.city;
          district = regionInfo.district;
          provinceCode = regionInfo.provinceCode;
          cityCode = regionInfo.cityCode;
          districtCode = regionInfo.districtCode;
          
          console.log('地图组件: 初始位置获取到省市区名称和代码', 
            { province, city, district },
            { provinceCode, cityCode, districtCode }
          );
        } catch (e) {
          console.error('解析地址上下文失败:', e);
        }
      }
      
      this.userlocation = {
        lng,
        lat,
        address: addressInfo?.place?.name || '',
        // 为拼班页面提供的字段
        province,
        city,
        district,
        // 为活动页面提供的字段
        provinceCode,
        cityCode,
        districtCode,
        ...addressInfo,
      };

      this.keywords = addressInfo?.place?.name || '';

      const marker = new aimap.Marker({ draggable: true }).setLngLat([lng, lat]).addTo(this.map);

      marker.on('dragend', async e => {
        const addressInfo = await this.getAddressInfo({ lng: e.target._lngLat.lng, lat: e.target._lngLat.lat });
        
        // 获取省市区信息
        let { province, city, district, provinceCode, cityCode, districtCode } = { province: '', city: '', district: '', provinceCode: '0', cityCode: '0', districtCode: '0' };
        
        if (addressInfo && addressInfo.address && addressInfo.address.context) {
          try {
            const context = addressInfo.address.context;
            
            console.log('拖动后位置context数据:', context);
            
            // 使用辅助函数获取省市区信息
            const regionInfo = this.getRegionInfo(context);
            province = regionInfo.province;
            city = regionInfo.city;
            district = regionInfo.district;
            provinceCode = regionInfo.provinceCode;
            cityCode = regionInfo.cityCode;
            districtCode = regionInfo.districtCode;
            
            console.log('拖动后位置省市区代码:', { provinceCode, cityCode, districtCode });
          } catch (e) {
            console.error('解析地址上下文失败:', e);
          }
        }
        
        // 确保拿到经纬度数据
        let lng = e.target._lngLat.lng;
        let lat = e.target._lngLat.lat;
        
        // 从返回的数据中获取位置名称
        let placeName = '';
        if (addressInfo && addressInfo.place && addressInfo.place.name) {
          placeName = addressInfo.place.name;
        } else if (addressInfo && addressInfo.address && addressInfo.address.name) {
          placeName = addressInfo.address.name;
        }
        
        this.userlocation = {
          lng,
          lat,
          address: placeName || '',
          // 为拼班页面提供的字段
          province,
          city,
          district,
          // 为活动页面提供的字段
          provinceCode,
          cityCode,
          districtCode,
          // 显式添加location对象，确保经纬度被正确传递
          location: {
            lng,
            lat
          },
          ...addressInfo,
        };
        
        this.keywords = placeName || '';
      });
    },

    // 获取地址信息
    async getAddressInfo(latLng) {
      const data = {
        asset: {},
        location: {
          position: {
            timestamp: +new Date(),
            point: {
              longitude: latLng.lng,
              latitude: latLng.lat,
            },
          },
        },
      };

      try {
        const response = await fetch(`https://api.newayz.com/location/hub/v1/track_points?access_key=${mapKey}`, {
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
          method: 'POST',
          mode: 'cors',
          credentials: 'omit',
        });

        if (!response.ok) {
          throw new Error('Network response was not ok ' + response.statusText);
        }

        const res = await response.json();
        
        // 打印完整的返回数据，检查adcode在哪里
        console.log('地图API返回完整数据:', JSON.stringify(res.location));
        
        if (res.location && res.location.address && res.location.address.context) {
          console.log('地址context数据:', 
            res.location.address.context.map(ctx => ({
              name: ctx.name,
              adcode: ctx.adcode,
              code: ctx.code,
              fullObject: ctx
            }))
          );
        }
        
        // 为返回的数据添加lng和lat字段，方便后续处理
        if (res.location && res.location.position && res.location.position.point) {
          res.location.lng = res.location.position.point.longitude;
          res.location.lat = res.location.position.point.latitude;
        }
        
        return res.location;
      } catch (err) {
        console.log('err', err);
        return null;
      }
    },

    // 搜索地址
    querySearch(value) {
      if (!value) {
        this.searchResults = [];
        return;
      }

      fetch(`https://api.newayz.com/location/scenario/v1/geocode?access_key=${mapKey}&address=${value}&callback=callback_jsonp_5`, {
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: null,
        method: 'GET',
        mode: 'cors',
        credentials: 'omit',
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
          }
          return response.json();
        })
        .then(res => {
          console.log('res', res);
          this.searchResults = res;
        })
        .catch(err => {
          console.log('err', err);
          this.searchResults = [];
        });
    },

    // 选择搜索结果
    handleSelect(item) {
      const { geoPoint } = item;
      const location = geoPoint.split(',');
      
      // 从item中获取省市区信息
      let { province, city, district, provinceCode, cityCode, districtCode } = { province: '', city: '', district: '', provinceCode: '0', cityCode: '0', districtCode: '0' };
      
      if (item.address && item.address.context) {
        try {
          const context = item.address.context;
          console.log('搜索结果context数据:', context);
          
          // 使用辅助函数获取省市区信息
          const regionInfo = this.getRegionInfo(context);
          province = regionInfo.province;
          city = regionInfo.city;
          district = regionInfo.district;
          provinceCode = regionInfo.provinceCode;
          cityCode = regionInfo.cityCode;
          districtCode = regionInfo.districtCode;
          
          console.log('地图组件: 搜索结果获取到省市区名称和代码', 
            { province, city, district },
            { provinceCode, cityCode, districtCode }
          );
        } catch (e) {
          console.error('解析地址上下文失败:', e);
        }
      }
      
      this.userlocation = {
        ...item,
        location: {
          lng: location[0],
          lat: location[1],
        },
        // 为拼班页面提供的字段
        province: province,
        city: city,
        district: district,
        // 为活动页面提供的字段
        provinceCode: provinceCode,
        cityCode: cityCode,
        districtCode: districtCode,
        address: item.name,
      };
      this.keywords = item.name || '';

      // 更新地图位置和标记
      this.map.setCenter([location[0], location[1]]);
      
      const marker = new aimap.Marker({ draggable: true }).setLngLat([location[0], location[1]]).addTo(this.map);

      marker.on('dragend', async e => {
        const addressInfo = await this.getAddressInfo({ lng: e.target._lngLat.lng, lat: e.target._lngLat.lat });
        
        // 获取省市区信息
        let { province, city, district, provinceCode, cityCode, districtCode } = { province: '', city: '', district: '', provinceCode: '0', cityCode: '0', districtCode: '0' };
        
        if (addressInfo && addressInfo.address && addressInfo.address.context) {
          try {
            const context = addressInfo.address.context;
            
            console.log('拖动后位置context数据:', context);
            
            // 使用辅助函数获取省市区信息
            const regionInfo = this.getRegionInfo(context);
            province = regionInfo.province;
            city = regionInfo.city;
            district = regionInfo.district;
            provinceCode = regionInfo.provinceCode;
            cityCode = regionInfo.cityCode;
            districtCode = regionInfo.districtCode;
            
            console.log('拖动后位置省市区代码:', { provinceCode, cityCode, districtCode });
          } catch (e) {
            console.error('解析地址上下文失败:', e);
          }
        }
        
        // 确保拿到经纬度数据
        let lng = e.target._lngLat.lng;
        let lat = e.target._lngLat.lat;
        
        // 从返回的数据中获取位置名称
        let placeName = '';
        if (addressInfo && addressInfo.place && addressInfo.place.name) {
          placeName = addressInfo.place.name;
        } else if (addressInfo && addressInfo.address && addressInfo.address.name) {
          placeName = addressInfo.address.name;
        }
        
        this.userlocation = {
          lng,
          lat,
          address: placeName || '',
          // 为拼班页面提供的字段
          province,
          city,
          district,
          // 为活动页面提供的字段
          provinceCode,
          cityCode,
          districtCode,
          // 显式添加location对象，确保经纬度被正确传递
          location: {
            lng,
            lat
          },
          ...addressInfo,
        };
        
        this.keywords = placeName || '';
      });

      this.keywords = item.name;
      this.searchResults = [];
    },

    // 获取当前位置
    setCurrentLocation() {
      return new Promise((resolve, reject) => {
        fetch(`https://api.newayz.com/positioning/ip/v1/ips?access_key=${mapKey}`, {
          referrerPolicy: 'strict-origin-when-cross-origin',
          body: null,
          method: 'GET',
          mode: 'cors',
          credentials: 'omit',
        })
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
          })
          .then(res => {
            const { latitude, longitude } = res.location.position.point;
            resolve({ latitude, longitude });
          })
          .catch(err => {
            console.log('err', err);
            reject(err);
          });
      });
    },

    // 初始化位置
    async initLocation() {
      try {
        const position = await this.setCurrentLocation();
        await this.initMap(position);
      } catch (error) {
        console.error('初始化位置失败：', error);
        await this.initMap();
      }
    },

    // 取消按钮
    handleCancel() {
      this.$emit('cancel');
    },

    // 确认选择
    handlerSelectConfirm() {
      if (!this.userlocation.address) {
        uni.showToast({
          title: '请选择位置',
          icon: 'none',
        });
        return;
      }

      // 提取省市区名称和代码
      const province = this.userlocation.province || '';
      const city = this.userlocation.city || '';
      const district = this.userlocation.district || '';
      
      // 尝试获取省市区代码，确保它们是有效的值
      let provinceCode = this.userlocation.provinceCode || '0';
      let cityCode = this.userlocation.cityCode || '0';
      let districtCode = this.userlocation.districtCode || '0';
      
      // 确保代码是有效的值
      if (provinceCode === 'undefined' || provinceCode === 'null' || !provinceCode) provinceCode = '0';
      if (cityCode === 'undefined' || cityCode === 'null' || !cityCode) cityCode = '0';
      if (districtCode === 'undefined' || districtCode === 'null' || !districtCode) districtCode = '0';
      
      // 尝试为湖南长沙设置固定值（临时解决方案）
      if (province.includes('湖南') || city.includes('长沙')) {
        provinceCode = '430000';
        cityCode = '430100';
      }
      
      // 确保address是字符串
      let addressStr = '';
      if (typeof this.userlocation.address === 'string') {
        addressStr = this.userlocation.address;
      } else if (typeof this.userlocation.address === 'object' && this.userlocation.address !== null) {
        // 如果address是对象，尝试获取name属性
        addressStr = this.userlocation.address.name || '';
      }
      
      console.log('地图组件: 确认选择位置，处理后的数据', {
        province, city, district,
        provinceCode, cityCode, districtCode,
        address: addressStr,
        location: this.userlocation.location
      });

      // 构建发送的数据对象
      const resultData = {
        ...this.userlocation,
        // 确保同时包含拼班和活动页面需要的字段
        province,
        city,
        district,
        provinceCode,
        cityCode,
        districtCode,
        // 确保address是字符串
        address: addressStr
      };
      
      // 删除address对象，避免重复
      if (typeof resultData.address === 'object') {
        delete resultData.address;
        resultData.address = addressStr;
      }

      this.$emit('select', resultData);
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  height: 100vh;
  background-color: #f5f5f5;
}
.info {
  padding-left: 0.5rem;
  margin-bottom: 1rem;
  border-radius: 0.25rem;
  position: fixed;
  top: 1rem;
  background-color: white;
  width: auto;
  min-width: 22rem;
  border-width: 0;
  right: 1rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
}
.search-box {
  width: 100%;
  position: absolute;
  top: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  background: #fff;
  padding: 0 12px;
}

.search-list {
  margin-top: 10rpx;
  background-color: #fff;
  border-radius: 8rpx;
  max-height: 400rpx;
  overflow-y: auto;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.search-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;

  &:active {
    background-color: #f5f5f5;
  }
}

.item-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.item-address {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.map {
  width: 100%;
  height: 100%;
}
.location {
  width: 500px;
  color: #000;
  background: #fff;
  position: absolute;
  bottom: 100rpx;
  right: 0;
}
.bottom-btns {
  position: absolute;
  bottom: 40rpx;
  right: 40rpx;
  display: flex;
  gap: 20rpx;
}
</style>
